package tests.mytest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Dom {
	
	private static List<Node> elementOrder = new ArrayList<Node>();
	private static List<Node> elementOrderRev = new ArrayList<Node>();
	private static Map<Node, Integer> elementAttr = new HashMap<Node, Integer>();
	private static int count=0;
	public static void main(String... p) throws Exception {
		
		
    	File f = new File("myfile.xml");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    	DocumentBuilder builder = factory.newDocumentBuilder();
    	Document document = builder.parse(f);
		
    	Node root = document.getDocumentElement();

    	ElementTreeWalker walker = new OrderSaver(elementOrder);
    	walker.walk(root);
    	
    	walker = new ReversingTreeWalker();
    	walker.walk(root);
    	
    	walker = new OrderSaver(elementOrderRev);
    	walker.walk(root);
    	
    	
		int i = 0;
    	for (Node n : elementOrder) {
    		System.out.println(i++ +" --> "+n);
    	}
    	i = 0;
    	for (Node n : elementOrderRev) {
    		System.out.println(i++ +" <-- "+n);
    	}
		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer = tFactory.newTransformer();
		DOMSource source = new DOMSource(document);
		StreamResult result = new StreamResult(System.out);
		transformer.transform(source, result); 

	
	
	}


	private static void reverseChildNodes(Node parent) {

		NodeList children = parent.getChildNodes();
		elementOrder.add(parent);
		elementAttr.put(parent, count++);
		List<Node> children2 = new ArrayList<Node>();
		for (int i=0; i<children.getLength(); i++) {
			Node child = children.item(i);
			processChildNode(child, children2);
		}
		for (int i=children2.size()-1; i>=0; i--) {
			parent.removeChild(children2.get(i));
			parent.appendChild(children2.get(i));
		}		
	}

	private static void processChildNode(Node child, List<Node> children) {
		
		if (child instanceof Element) {
			Element e = (Element)child;
			NamedNodeMap nnm = e.getAttributes();
			for (int i=nnm.getLength()-1; i>=0 ; i--) {
				e.removeAttribute(nnm.item(i).getNodeName());
			}
			e.setAttribute("c", "1");
			e.setAttribute("b", "3");
			e.setAttribute("a", "2");
			
			reverseChildNodes(child);
			children.add(child);
		}

	}
}
